<template>
  <div class="container">
    <van-sticky>
      <div class="bgc-color-white">
        <div class="pad-t-15 pad-l-15 pad-r-15">
          <div class="flex flex-center search-wrap" @click="$pt.navigateTo({url: '/pages/personal/commodity-library/search/main'})">
            <van-icon name="search" color="#aeaeae" size="14px" class="mar-t-2" />
            <span class="mar-l-6 font-color-9 font-12">搜索商品名称</span>
          </div>
        </div>
        <div class="tab-menu">
          <scroll-view
            class="horizontal-bar flex"
            :scroll-into-view="'category-top-' + currentCategory.categoryId"
            :scroll-x="true">
            <div
              class="item-bar flex-item"
              :id="leftMenuClick ? '' : 'category-top-' + item.categoryId"
              :class="{'item-bar--active': categoryActive === item.categoryId}"
              v-for="(item, index) in categoryList"
              :key="index"
              @click="tabClick(item, index)">
                <div class="item-txt">
                  {{item.categoryName}}
                  <div :class="{'leftline': categoryActive === item.categoryId}"></div>
                </div>              
            </div>
          </scroll-view>
          <div v-if="fileSpace" class="tab-more" :class="iosType ? '' : 'tab-more-and'" @click="tabLayerShow"
            :style="'background: url(' + fileSpace + '/images/w-icon-catedown-5.png) no-repeat'"></div>
        </div>
      </div>
    </van-sticky>
    <div class="main" v-if="!nodata" :class="tabLayer ? 'noscroll' : ''">
      <goods-block 
        :dataList="lowerGoodsList"
        blockType="0"
        :isRecommend="isRecommend"
        custom-style="margin-bottom: 10px" 
        @onUpdateShelfFlag="onUpdateShelfFlag('lowerGoodsList', $event)"
        @onSwitchChange="onSwitchChange('lowerGoodsList', $event)">
      </goods-block>
      <goods-block 
        :dataList="upperGoodsList"
        blockType="1"
        :isRecommend="isRecommend"
        custom-style="margin-bottom: 10px"
        @onUpdateShelfFlag="onUpdateShelfFlag('upperGoodsList', $event)"
        @onSwitchChange="onSwitchChange('upperGoodsList', $event)">
      </goods-block>
      <goods-block :dataList="sellOutGoodsList" blockType="2" custom-style="margin-bottom: 10px"></goods-block>
      <goods-block :dataList="invalidGoodsList" blockType="3" @clearInvalidBlock="clearInvalidBlock"></goods-block>
    </div>
    <div class="nodata" v-else>
      <div class="align-c" style="padding-top: 120px;">
        <img v-if="fileSpace" :src="fileSpace + '/images/shop-nodata.png'" class="width-375 height-91" alt="">
        <div class="align-c mar-t-5 font-16 font-color-6">
          暂无数据
        </div>
      </div>
    </div>
    <div class="float-bar" v-if="!isRecommend">
      <div class="float-btn" @click="updateShelfFlagByOneCategoryId">一键上架</div>
      <div class="float-btn mar-t-18 set-recommend" @click="setRecommend">设置推荐</div>
    </div>
    <div class="exit-setting" v-if="isRecommend" @click="exitRecommend">退出</div>
    <div @touchmove.prevent="">
      <van-popup
        :show="tabLayer"
        position="right"
        custom-style="width: 80%; height: 100%;"
        @close="onPopupClose"
      >
        <div class="popup-layer">
          <h3>状态</h3>
          <ul>
            <li v-for="(item, index) in statusList" :key="index">
              <div class="li-item" :class="{'active': statusActive === item.upperShelfFlag}" @click="onStatusClick(item)">{{item.text}}</div>
            </li>
          </ul>
          <h3>推荐</h3>
          <ul>
            <li v-for="(item, index) in recommendList" :key="index">
              <div class="li-item" :class="{'active': recommendActive === item.showHomePage}" @click="onRecommendClick(item)">{{item.text}}</div>
            </li>
          </ul>
          <h3>分类</h3>
          <ul>
            <li v-for="(item, index) in categoryList" :key="index">
              <div class="li-item" :class="{'active': categoryActive === item.categoryId}" @click="onCategoryClick(item)">{{item.categoryName}}</div>  
            </li>
          </ul>
          <div class="bottom-btn flex flex-between pad-l-15 pad-r-15">
            <div class="reset-btn" @click="resetCondition">重置</div>
            <div class="comfirm-btn" @click="confirmCondition">确定</div>
          </div>
        </div>
      </van-popup>
    </div>
  </div>
</template>
<script>
import GoodsBlock from './component/goods-block/index'
import {
  listOneGoodsCategory,
  pagingGoodsSelection,
  updateShelfFlag,
  updateShowHomePage,
  updateShelfFlagByOneCategoryId,
  deleteInvalidGoods
} from '@/api/personal'
export default {
  components: { GoodsBlock },
  data() {
    return {
      goodsCount: 0,
      leftMenuClick: false,
      currentCategory: {
        categoryId: '1'
      },
      tabLayer: false,
      statusActive: '',
      statusList: [{
        upperShelfFlag: '',
        text: '全部'
      }, {
        upperShelfFlag: 0,
        text: '待上架'
      }, {
        upperShelfFlag: 1,
        text: '已上架'
      }],
      isRecommend: false,
      recommendActive: '',
      recommendList: [{
        showHomePage: '',
        text: '全部'
      }, {
        showHomePage: 0,
        text: '待设置'
      }, {
        showHomePage: 1,
        text: '已设置'
      }],
      categoryActive: '',
      categoryList: [],
      checked: false,
      upperGoodsList: [],
      lowerGoodsList: [],
      sellOutGoodsList: [],
      invalidGoodsList: [],
      paddingParams: {
        memberId: '',
        enterpriseId: '',
        title: '',
        oneCategoryId: '',
        upperShelfFlag: '',
        showHomePage: '',
        size: 10,
        currentPage: 1
      },
      pullLoad: {
        finished: false,
        loading: false
      },
      recordsCount: 0,
      nodata: false
    }
  },
  onShow() {
    this.paddingParams.memberId = this.getCustomerId
    this.paddingParams.enterpriseId = this.getEnterpriseId
    // 判断从详情页返回的数据状态是否发生更改
    const pages = getCurrentPages() // eslint-disable-line
    let curPage = pages[pages.length - 1]
    let goods = curPage.data.goods
    if (goods) {
      let arrayName = ''
      switch (goods.blockType) {
        case '0':
          arrayName = 'lowerGoodsList'
          break
        case '1':
          arrayName = 'upperGoodsList'
          break
        case '2':
          arrayName = 'sellOutGoodsList'
          break
        case '3':
          arrayName = 'invalidGoodsList'
          break
        default:
          break
      }
      let index = this[arrayName].findIndex(item => item.goodsId === goods.goodsId)
      this.$delete(this[arrayName][index], 'upperShelfFlag')
      this.$delete(this[arrayName][index], 'showHomePage')
      this.$set(this[arrayName][index], 'upperShelfFlag', goods.upperShelfFlag)
      this.$set(this[arrayName][index], 'showHomePage', goods.showHomePagev)
      curPage.setData({ goods: null })
    }
    this.init()
  },
  onReachBottom() {
    // 触底刷新
    if (!this.pullLoad.finished) {
      this.pagingGoodsSelection()
    }
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.listOneGoodsCategory()
    this.resetData()
    this.statusActive = ''
    this.recommendActive = ''
    this.pagingGoodsSelection()
    setTimeout(() => {
      this.$pt.stopPullDownRefresh()
    }, 500)
  },
  methods: {
    init() {
      this.listOneGoodsCategory()
      this.pagingGoodsSelection()
    },
    tabClick(item) {
      this.categoryActive = item.categoryId
      this.currentCategory.categoryId = item.categoryId
      this.resetData()
      this.pagingGoodsSelection()
    },
    resetData() {
      this.paddingParams.currentPage = 1
      this.recordsCount = 0
      this.lowerGoodsList = []
      this.upperGoodsList = []
      this.sellOutGoodsList = []
      this.invalidGoodsList = []
      this.pullLoad.finished = false
    },
    tabLayerShow() {
      this.tabLayer = true
    },
    onPopupClose() {
      this.tabLayer = false
    },
    onStatusClick(item) {
      this.statusActive = item.upperShelfFlag
    },
    onRecommendClick(item) {
      this.recommendActive = item.showHomePage
    },
    onCategoryClick(item) {
      this.categoryActive = item.categoryId
      this.currentCategory.categoryId = item.categoryId
    },
    resetCondition() {
      // 重置筛选条件
      this.statusActive = ''
      this.recommendActive = ''
      this.categoryActive = ''
      this.currentCategory.categoryId = ''
      this.resetData()
      this.pagingGoodsSelection()
      this.onPopupClose()
    },
    confirmCondition() {
      this.resetData()
      this.pagingGoodsSelection()
      this.onPopupClose()
    },
    onSwitchChange(arrayName, ev) {
      this.updateShowHomePage(arrayName, ev.mp.details.goodsId, ev.mp.details.showHomePage)
    },
    setRecommend() {
      // 设置推荐
      // this.isRecommend = true
      this.$pt.navigateTo({ url: '/pages/shop/recommend/main' })
    },
    exitRecommend() {
      // 退出设置推荐
      this.isRecommend = false
    },
    clearInvalidBlock() {
      // 清空失效商品
      this.deleteInvalidGoods()
    },
    listOneGoodsCategory() {
      // 获取商品分类列表
      listOneGoodsCategory({
        enterpriseId: this.getEnterpriseId,
        memberId: this.getMemberId
      }).then(response => {
        if (response.isError) return
        this.categoryList = response.data || []
        this.categoryList.unshift({
          categoryId: '',
          categoryName: '全部'
        })
      }).catch(() => {
      })
    },
    pagingGoodsSelection() {
      // 获取商品数据列表
      this.paddingParams.oneCategoryId = this.categoryActive
      this.paddingParams.upperShelfFlag = this.statusActive
      this.paddingParams.showHomePage = this.recommendActive
      pagingGoodsSelection(this.paddingParams).then(response => {
        if (response.isError) return
        this.goodsCount = response.data.total
        this.$pt.setNavigationBarTitle({
          title: `商品库(${this.goodsCount})`
        })
        let list = response.data.records
        list.forEach(element => {
          this.recordsCount++
          switch (element.upperShelfFlag) {
            case 0:
              this.lowerGoodsList.push(element)
              break
            case 1:
              this.upperGoodsList.push(element)
              break
            case 2:
              this.sellOutGoodsList.push(element)
              break
            case 3:
              this.invalidGoodsList.push(element)
              break
            default:
              break
          }
        })
        if (this.paddingParams.currentPage === 1) {
          if (this.upperGoodsList.length > 0 || this.lowerGoodsList.length > 0 || this.sellOutGoodsList.length > 0 || this.invalidGoodsList.length > 0) {
            this.nodata = false
          } else {
            this.nodata = true
          }
        }
        this.paddingParams.currentPage++
        if (this.recordsCount >= response.data.total || this.recordsCount === 0) {
          this.pullLoad.finished = true
        }
      }).catch(() => {
      })
    },
    updateShelfFlag(arrayName, goodsId, upperShelfFlag) {
      // 商品上下架
      let params = {
        memberId: this.getCustomerId,
        upperShelfFlag: upperShelfFlag,
        goodsId: goodsId
      }
      updateShelfFlag(params).then(response => {
        if (response.isError) return
        this.$utils.showToast({
          title: upperShelfFlag === 1 ? '上架成功' : '下架成功'
        })
        let index = this[arrayName].findIndex(item => item.goodsId === goodsId)
        this[arrayName][index].upperShelfFlag = upperShelfFlag
        if (upperShelfFlag === 0) {
          this[arrayName][index].showHomePage = 0
          this.$delete(this[arrayName][index], 'showHomePage')
          this.$set(this[arrayName][index], 'showHomePage', 0)
        }
        this.$delete(this[arrayName][index], 'upperShelfFlag')
        this.$set(this[arrayName][index], 'upperShelfFlag', upperShelfFlag)
      }).catch(() => {
      })
    },
    onUpdateShelfFlag(arrayName, ev) {
      if (ev.mp.details.upperShelfFlag === 0) {
        this.$pt.showModal({
          content: '下架商品后将对顾客隐藏该商品',
          confirmText: '确认下架',
          confirmColor: '#333',
          success: (res) => {
            if (res.confirm) {
              this.updateShelfFlag(arrayName, ev.mp.details.goodsId, ev.mp.details.upperShelfFlag)
            }
          }
        })
      } else {
        this.updateShelfFlag(arrayName, ev.mp.details.goodsId, ev.mp.details.upperShelfFlag)
      }
    },
    updateShowHomePage(arrayName, goodsId, showHomePage) {
      // 商品设置推荐
      let params = {
        memberId: this.getCustomerId,
        showHomePage: showHomePage,
        goodsId: goodsId
      }
      updateShowHomePage(params).then(response => {
        if (params.isError) return
        let index = this[arrayName].findIndex(item => item.goodsId === goodsId)
        this[arrayName][index].showHomePage = showHomePage
      }).catch(() => {
      })
    },
    updateShelfFlagByOneCategoryId() {
      // 一键上架
      this.$pt.showModal({
        content: '是否确认上架当前导航分类下所有未上架商品？',
        confirmText: '确认上架',
        confirmColor: '#333',
        success: (res) => {
          if (res.confirm) {
            let params = {
              memberId: this.getCustomerId,
              oneCategoryId: this.categoryActive
            }
            updateShelfFlagByOneCategoryId(params).then(response => {
              if (response.isError) return
              this.$utils.showToast({
                title: '上架成功'
              })
              this.resetData()
              this.pagingGoodsSelection()
            }).catch(() => {
            })
          }
        }
      })
    },
    deleteInvalidGoods() {
      // 删除失效商品
      this.$pt.showModal({
        content: '是否确认清空所有失效商品？',
        confirmText: '确认清空',
        confirmColor: '#333',
        success: (res) => {
          if (res.confirm) {
            deleteInvalidGoods({memberId: this.getCustomerId}).then(response => {
              if (response.isError) return
              this.$utils.showToast({
                title: '清空成功'
              })
              this.resetData()
              this.pagingGoodsSelection()
            }).catch(() => {
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.container{
  background-color: #F5F5F5;
  min-height: 100vh;
  .bgc-color-white{
    background-color: white;
  }
  .tab-menu{
    background: #fff;
    min-height: 44px;
    padding-right: 45px;
    box-sizing: border-box;
    width: 100%;
    position: relative;
    z-index: 10;
    border-bottom: 0.5px solid #eeeeee;
    .tab-more{
      width: 40px;
      height: 40px;
      position: absolute;
      right: 0;
      top: 2px;
      z-index: 11;
      background-size: 40px 40px!important;
      &.tab-more-and{
        top: 3px;
      }
    }
  }
  .horizontal-bar {
    height: 44px;
    white-space: nowrap;
    overflow-x: scroll;
    &:after{
      content: '';
      display: block;
      clear: both;
      font-size: 0;
    }
    .item-bar {
      display: inline-block;
      height: 44px;
      line-height: 44px;
      width: 72px;
      font-size: 16px;
      color: #333;
      font-size: 15px;
      text-align: center;
      overflow: hidden;
      .item-txt{
        display: inline-block;
        position: relative;
      }
      &--active {          
        font-weight: bold;
        .leftline {
          position: absolute;
          background: #FFE200;
          left: 50%;
          transform: translate(-50%);
          bottom: 6px;
          height: 3px;
          width: 18px;
          border-radius: 3px;
        }
      }
    }
  }
  .popup-layer{
    height: 100%;
    position: relative;
    box-sizing: border-box;
    padding-bottom: 70px;
    overflow-y: scroll;
    h3{
      line-height: 1;
      padding: 16px 15px 0;
      font-size: 15px;
      color: #333;
    }
    ul{
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: wrap;
      padding: 5px 15px 0;
      li{
        // flex-shrink: 0;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex: 0 0 calc(100% / 3);
        &:nth-child(3n + 1) {
          justify-content: flex-start;
        }
        &:nth-child(3n) {
          justify-content: flex-end;
        }
        .li-item{
          width: 76px;
          height: 32px;
          border-radius: 16px;
          background-color: #F5F5F5;
          font-size: 12px;
          color: #333;
          text-align: center;
          line-height: 32px;
          box-sizing: border-box;
            &.active{
            border: 1px solid #FFE200;
            background-color: #FFFBD8;
            width: 74px;
            height: 30px;
            line-height: 30px;
          }
        }
      }
    }
    .bottom-btn{
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      box-sizing: border-box;
      font-size: 16px;
      text-align: center;
      background-color: #fff;
      padding: 10px 15px;
      .reset-btn{
        width: 106px;
        height: 44px;
        border-radius: 22px;
        line-height: 44px;
        background-color: #F5F5F5;
        color: #666;
      }
      .comfirm-btn{
        width: 152px;
        height: 44px;
        line-height: 44px;
        border-radius: 22px;
        background-color: #FFE100;
        color: #333;
      }
    }
  }
  .noscroll{
    overflow: hidden;
    height: calc(100vh - 94px);
  }
  .main{
    .font-red{
      color: #EB4E4E;
    }
    .invalid-tag{
      color: white;
      background-color: #999;
      border-radius: 7.25px;
      width: 30px;
      height: 15px;
      text-align: center;
      line-height: 15px;
      font-size: 11px;
    }
    ul{
      &.invalid-ul{
        position: relative;
        &::after{
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          background-color: #fff;
          opacity: .5;
        }
      }
      li{
        .v-flex-between{
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: flex-start;
        }
        .width-100p{
          width: 100%;
        }
        .radius-5{
          border-radius: 5px;
        }
        .bc-yellow{
          background-color: #FFD800;
        }
        .bc-gray{
          background-color: #E5E5E5;
        }
        .recommend{
          position: absolute;
          left: 0;
          top: 0;
          border-radius: 5px 0 5px 0;
          padding: 0px 8px;
          background-color: rgba(0, 0, 0, .5);
          color: white;
          font-size: 12px;
        }
        .namespace{
          .namespace-l{
            padding: 2px 4px;
            background-color: #FED807;
          }
          .namespace-r{
            padding: 2px 4px;
            background-color:#272727;
            color: white;
            border-radius: 0 2px 2px 0;
          }
        }
        .seckill{
          display: flex;
          align-items: center;
          justify-content: flex-start;
          line-height: 20px;
          .seckill-l{
            height: 20px;
            line-height: 20px;
            padding: 0 4px;
            background-color: #272727;
            color: white;
            border-radius: 4px 0 0 4px;
          }
          .seckill-r{
            height: 20px;
            padding: 0 4px;
            background-color: #FED807;
          }
        }
        /deep/._van-switch{
          height: 20px;
        }
        .upper-status{
          border-radius: 11px;
          width: 49px;
          height: 22px;
          line-height: 22px;
          text-align: center;
          font-size: 12px;
        }
      }
    }
  }
  .float-bar{
    position: fixed;
    left: 15px;
    bottom: 38px;
    .float-btn{
      width: 45px;
      height: 45px;
      border-radius: 50%;
      background-color: #FFE100;
      text-align: center;
      font-size: 11px;
      padding: 9px 10px;
      box-sizing: border-box;
      font-weight: bold;
      line-height: 1.2;
    }
    .set-recommend{
      background-color: #FFFCE5;
    }
  }
  .exit-setting{
    width: 240px;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-size: 16px;
    color: white;
    background-color: #FF3B3B;
    border-radius: 22px;
    position: fixed;
    left: 50%;
    bottom: 38px;
    transform: translateX(-50%);
  }
}
.search-wrap{
  background-color: #f6f6f6;
  border-radius: 15px;
  height: 34px;
}
</style>
